package com.lepu.app.fun.index.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.app.config.AppConfig;
import com.app.config.UserConfig;
import com.app.utils.Const;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.core.lib.adapter.FragmentPageAdapter;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.lepu.app.fun.index.bean.BeanIndexVideoPoint;
import com.lepu.app.fun.index.fragment.FragmentVideo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;

import org.json.JSONObject;

public class IndexVideoActivity extends BaseFragmentActivity implements
        OnTopbarNewLeftLayoutListener, AsyncRequest {
    private ViewPager mViewPager = null;
    private LinearLayout mTabLayoutOne = null;
    private LinearLayout mTabLayoutTwo = null;
    private LinearLayout mTabLayoutThree = null;
    private static final String REQUEST_DATA = "request_data";
    private static final int MSG_DATA_SUCCESS = 55;
    private static final int MSG_DATA_FAIL = 56;

    private int mCurrentTab = 0;

    public ArrayList<Fragment> fragmentList;
    private ArrayList<ImageView> mTabPointList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mNeedDefaultUmeng = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.index_video_activity);

        init();
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    /**
     * 添加页面动画，需要重写这个方法，
     */
    @Override
    public void onBackPressed() {
        finish(true);
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
        finish(true);
    }

    private void init() {
        // topbar
        CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
        topbar.setTopbarTitle("视频集粹");
        topbar.setonTopbarNewLeftLayoutListener(this);

        fragmentList = new ArrayList<Fragment>();
        FragmentVideo bbs1 = new FragmentVideo();
        FragmentVideo bbs2 = new FragmentVideo();
        FragmentVideo bbs3 = new FragmentVideo();

        Bundle data1 = new Bundle();
        data1.putString("ArticleTag", "用药管理");
        data1.putInt("Type", 0);
        data1.putSerializable("MotherCircle", null);
        bbs1.setArguments(data1);

        Bundle data2 = new Bundle();
        data2.putString("ArticleTag", "动漫系列");
        data1.putInt("Type", 1);
        data2.putSerializable("MotherCircle", null);
        bbs2.setArguments(data2);

        Bundle data3 = new Bundle();
        data3.putString("ArticleTag", "百科讲座");
        data1.putInt("Type", 2);
        data3.putSerializable("MotherCircle", null);
        bbs3.setArguments(data3);

        fragmentList.add(bbs1);
        fragmentList.add(bbs2);
        fragmentList.add(bbs3);

        mViewPager = (ViewPager) findViewById(R.id.motherCircleListViewPager);
        mViewPager.setAdapter(new FragmentPageAdapter(getSupportFragmentManager(), fragmentList, null, null));
        mViewPager.setOnPageChangeListener(new MyViewChangeListener());
        mViewPager.setOffscreenPageLimit(2);

        mTabLayoutOne = (LinearLayout) findViewById(R.id.tabLayout1);
        mTabLayoutTwo = (LinearLayout) findViewById(R.id.tabLayout2);
        mTabLayoutThree = (LinearLayout) findViewById(R.id.tabLayout3);

        mTabLayoutOne.setOnClickListener(mViewClickListener);
        mTabLayoutTwo.setOnClickListener(mViewClickListener);
        mTabLayoutThree.setOnClickListener(mViewClickListener);

        mTabPointList = new ArrayList<ImageView>();

        mTabPointList.add((ImageView) findViewById(R.id.tab_point1));
        mTabPointList.add((ImageView) findViewById(R.id.tab_point2));
        mTabPointList.add((ImageView) findViewById(R.id.tab_point3));

        showRed();

        request();

//        mTabPointList.get(0).setVisibility(View.GONE);

        updateTabLine(mCurrentTab);

    }

    //显示红点
    private void showRed() {

        ImageView tab_point1 = (ImageView)findViewById(R.id.tab_point1);
        ImageView tab_point2 = (ImageView)findViewById(R.id.tab_point2);
        ImageView tab_point3 = (ImageView)findViewById(R.id.tab_point3);

        int count_yygl = UserConfig.getConfigInt(this, Const.CONFIG_YYGL, 0);
        int count_dmxl = UserConfig.getConfigInt(this, Const.CONFIG_DMXL, 0);
        int count_bkjz = UserConfig.getConfigInt(this, Const.CONFIG_BKJZ, 0);

        if(count_yygl > 0){
            tab_point1.setVisibility(View.VISIBLE);
        }else {
            tab_point1.setVisibility(View.GONE);
        }

        if(count_dmxl > 0){
            tab_point2.setVisibility(View.VISIBLE);
        }else {
            tab_point2.setVisibility(View.GONE);
        }

        if(count_bkjz > 0){
            tab_point3.setVisibility(View.VISIBLE);
        }else {
            tab_point3.setVisibility(View.GONE);
        }

    }

    private void request() {

        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject params = new JSONObject();
        try {
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);
            params.put("DeviceSN", AppManager.getDeviceUniqueId(this));

            if (LoginUtil.checkIsLogin()) {
                params.put("UserID", LoginUtil.getUserId());
                params.put("LoginToken", LoginUtil.getLoginToken());
            } else {
                params.put("UserID", -1);
                params.put("LoginToken", "");
            }

            params.put("AfterTime", getDateTime());

        } catch (Exception e) {
        }
        map.put("ht", params);

        String url = Setting.getIndexVideoPointUrl();

        ApiClient.http_post(url, map, null, this, REQUEST_DATA, true, false,
                true);
    }

    private String getDateTime() {

        String lastTime =  UserConfig.getConfigString(this, Const.CONFIG_CURRENTTIME, "");

        if(!TextUtils.isEmpty(lastTime)){
            LogUtilBase.LogD("TAG", "上次请求的时间是=========>" + lastTime);
            return  lastTime;
        }else {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date curDate = new Date(System.currentTimeMillis());//获取当前时间
            String time = formatter.format(curDate);

            UserConfig.setConfig(IndexVideoActivity.this, Const.CONFIG_CURRENTTIME, time);
            LogUtilBase.LogD("TAG", "这次请求时间是=========>" + time);
            return time;
        }

    }

    View.OnClickListener mViewClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            ImageView tab_point1 = (ImageView)findViewById(R.id.tab_point1);
            ImageView tab_point2 = (ImageView)findViewById(R.id.tab_point2);
            ImageView tab_point3 = (ImageView)findViewById(R.id.tab_point3);
            switch (v.getId()) {
                case R.id.tabLayout1:
                    tab_point1.setVisibility(View.GONE);
                    UserConfig.setConfig(IndexVideoActivity.this, Const.CONFIG_YYGL, 0);
                    if (mCurrentTab == 0)
                        return;

                    UmengHelper.CustomEvent(IndexVideoActivity.this, UmengEvent.event_shouye_shipinjicui_yongaoguanli);
                    mViewPager.setCurrentItem(0, false);
                    updateTabLine(0);
                    break;

                case R.id.tabLayout2:

                    tab_point2.setVisibility(View.GONE);
                    UserConfig.setConfig(IndexVideoActivity.this, Const.CONFIG_DMXL, 0);
                    if (mCurrentTab == 1)
                        return;

                    UmengHelper.CustomEvent(IndexVideoActivity.this, UmengEvent.event_shouye_shipinjicui_dongmanxilie);
                    mViewPager.setCurrentItem(1, false);
                    updateTabLine(1);
                    break;
                case R.id.tabLayout3:

                    tab_point3.setVisibility(View.GONE);
                    UserConfig.setConfig(IndexVideoActivity.this, Const.CONFIG_BKJZ, 0);

                    if (mCurrentTab == 2)
                        return;

                    UmengHelper.CustomEvent(IndexVideoActivity.this, UmengEvent.event_shouye_shipinjicui_baikejiangzuo);
                    mViewPager.setCurrentItem(2, false);
                    updateTabLine(2);
                    break;

                default:
                    break;
            }
        }
    };

    private void updateTabLine(int currentIndex) {

        if (currentIndex == 0) {
            mTabLayoutOne.setSelected(true);
            mTabLayoutTwo.setSelected(false);
            mTabLayoutThree.setSelected(false);

        } else if (currentIndex == 1) {
            mTabLayoutOne.setSelected(false);
            mTabLayoutTwo.setSelected(true);
            mTabLayoutThree.setSelected(false);

        } else if (currentIndex == 2) {
            mTabLayoutOne.setSelected(false);
            mTabLayoutTwo.setSelected(false);
            mTabLayoutThree.setSelected(true);
        }
    }


    class MyViewChangeListener implements OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int arg2) {

        }

        @Override
        public void onPageSelected(int index) {
            mCurrentTab = index;
            mViewPager.setCurrentItem(index, false);
            updateTabLine(index);

            mTabPointList.get(index).setVisibility(View.GONE);
            setMsgData(index);
        }


    }

    //红点归零
    private void setMsgData(int index) {
        switch (index){
            case 0:
                UserConfig.setConfig(IndexVideoActivity.this, Const.CONFIG_YYGL, 0);

                break;
            case 1:
                UserConfig.setConfig(IndexVideoActivity.this, Const.CONFIG_DMXL, 0);
                break;
            case 2:

                UserConfig.setConfig(IndexVideoActivity.this, Const.CONFIG_BKJZ, 0);
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MSG_DATA_SUCCESS:

                    BeanIndexVideoPoint beanPoint = (BeanIndexVideoPoint)msg.obj;

                    int count_yygl = UtilityBase.parseInt( beanPoint.ArticleCount_yygl);
                    int count_dmxl = UtilityBase.parseInt( beanPoint.ArticleCount_dmxl);
                    int count_bkjz = UtilityBase.parseInt( beanPoint.ArticleCount_bkjz);

                    String currentTime = beanPoint.CurrentTime;

                    LogUtilBase.LogD("TAG", "用药管理--新增消息数量：=========>" + count_yygl);
                    LogUtilBase.LogD("TAG", "动漫系列--新增消息数量：=========>" + count_dmxl);
                    LogUtilBase.LogD("TAG", "百科讲座--新增消息数量：=========>" + count_bkjz);

                    ImageView tab_point1 = (ImageView)findViewById(R.id.tab_point1);
                    ImageView tab_point2 = (ImageView)findViewById(R.id.tab_point2);
                    ImageView tab_point3 = (ImageView)findViewById(R.id.tab_point3);

                    if(count_yygl > 0){

                        UserConfig.setConfig(IndexVideoActivity.this, Const.CONFIG_YYGL, count_yygl);
                        tab_point1.setVisibility(View.VISIBLE);
                    }

                    if(count_dmxl > 0){
                        UserConfig.setConfig(IndexVideoActivity.this, Const.CONFIG_DMXL, count_dmxl);
                        tab_point2.setVisibility(View.VISIBLE);
                    }

                    if(count_bkjz > 0){
                        UserConfig.setConfig(IndexVideoActivity.this, Const.CONFIG_BKJZ, count_bkjz);

                        tab_point3.setVisibility(View.VISIBLE);
                    }

                    if(count_bkjz + count_yygl + count_dmxl > 0 && !TextUtils.isEmpty(currentTime)){

                        UserConfig.setConfig(IndexVideoActivity.this, Const.CONFIG_CURRENTTIME, currentTime);
                    }

                    break;
                case MSG_DATA_FAIL:

                    break;
            }
        };
    };


    @Override
    public void RequestComplete(Object object, Object data) {

        if (object.equals(REQUEST_DATA)) {
            BeanIndexVideoPoint dataString = BeanIndexVideoPoint.parseListInfo((String) data);

            Message msg = mHandler.obtainMessage();
            msg.what = MSG_DATA_SUCCESS;
            msg.obj = dataString;
            mHandler.sendMessage(msg);

        }

    }

    @Override
    public void RequestError(Object object, int i, String data) {

        if (object.equals(REQUEST_DATA)) {
            Message msg = mHandler.obtainMessage();
            msg.what = MSG_DATA_FAIL;
            mHandler.sendMessage(msg);
        }

    }

}
